package org.kl.bpm.service.conf;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bpm.entity.conf.BpmKvRecord;
import org.kl.bpm.repository.conf.BpmKvRecordDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

/**
 * 
 * @Author hqm
 * @CreateTime 2014年5月25日 下午8:40:29
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class BpmKvRecordService {

	private BpmKvRecordDao bpmKvRecordDao;

	public BpmKvRecord getBpmKvRecord(String id) {
		if (StringUtils.isBlank(id))
			return null;
		else
			return bpmKvRecordDao.findOne(id);
	}

	public BpmKvRecord findByRef(String ref) {
		return bpmKvRecordDao.findByRef(ref);
	}

	public void saveBpmKvRecord(BpmKvRecord entity) {
		bpmKvRecordDao.save(entity);
	}

	public void deleteBpmKvRecord(String id) {
		bpmKvRecordDao.delete(id);
	}

	public List<BpmKvRecord> getAllBpmKvRecord() {
		return bpmKvRecordDao.findAll();
	}
	
	public BpmKvRecord findByBusinessId(String businessId) {
		return bpmKvRecordDao.findByBusinessId(businessId);
	}

	public Page<BpmKvRecord> getUserBpmKvRecord(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<BpmKvRecord> spec = buildSpecification(searchParams);

		return bpmKvRecordDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<BpmKvRecord> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<BpmKvRecord> spec = DynamicSpecifications.bySearchFilter(filters.values(), BpmKvRecord.class);
		return spec;
	}

	@Autowired
	public void setBpmKvRecordDao(BpmKvRecordDao bpmKvRecordDao) {
		this.bpmKvRecordDao = bpmKvRecordDao;
	}

}
